package com.ruoyi.recyclecomprehensive.aspect;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.recycle.domain.MerchantManagement;
import com.ruoyi.recycle.dto.HousekeepingOrderQueryDTO;
import com.ruoyi.recycle.dto.RecycleOrderDTO;
import com.ruoyi.recycle.exception.BusinessException;
import com.ruoyi.recycle.service.IMerchantManagementService;
import com.ruoyi.recyclecomprehensive.annotion.CheckUser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@Slf4j
@Aspect
public class AccountCheckAspect {
    @Autowired
    private IMerchantManagementService merchantManagementService;

    @Before(value = "@annotation(checkUser)")
    public void doBefore(JoinPoint joinPoint, CheckUser checkUser) {
        final Object[] args = joinPoint.getArgs();
        final String username = SecurityUtils.getUsername();
        final MerchantManagement loginUser = merchantManagementService.getOne(Wrappers.lambdaQuery(new MerchantManagement())
                .eq(MerchantManagement::getMerchantNumber, username));
        Assert.isFalse(Objects.isNull(loginUser), () -> new BusinessException("登陆的账号信息为空"));
        for (Object arg : args) {
            if (arg instanceof HousekeepingOrderQueryDTO) {
                if (!((HousekeepingOrderQueryDTO) arg).getMerchantId().equals(loginUser.getId())) {
                    throw new BusinessException("查询家政订单的综合站的ID和登录的ID不符");
                }
            } else if (arg instanceof RecycleOrderDTO) {
                if (!((RecycleOrderDTO) arg).getMerchantId().equals(loginUser.getId())) {
                    throw new BusinessException("查询回收订单的综合站的ID和登录的ID不符");

                }
            }
        }
    }
}
